#include "WorkerThread.h"
#include <stdio.h>
#include "gracesc.h"
#include <stdio.h>
#include "proto.h"

WorkerThread::WorkerThread(){
	done=false;
	//initializeGraph();
}

void WorkerThread::setDialog(Proto* p){
	dialog=p;
}

void WorkerThread::stop(){
	done=true;
}

void WorkerThread::run(){
	gracesc::Xmgrace graph("param.par",1);
	initializeGraph();
	done=false;
	FILE* last = fopen("Position.dat","r");

	//if we're starting up a new day, read last odometer reading, else start from scratch
	if(last  != NULL)
		fscanf(last,"%d",&dialog->odometer);
	if(dialog->odometer == NULL)
		dialog -> odometer = 0;
	FILE* record;

	//open file for data logging	
	if((record=fopen("data.dat","a"))==NULL)
	{
		fprintf(stderr,"ERROR: Can not log data\n");
	}

	//main loop reads data from the car, logs it to file, graphs appropriate data nd updates the dashboard
	while(!done){
		//Here, we get data and write to global buffer (creates a packet)
		// ---**this command should be replaced by serial port code**
		sprintf(dialog->buffer,"ABCDEF\r\nTI %d\r\nOD %d\r\nTM %d\r\nTC %d\r\nVO %d\r\nCU %d\r\nSP %d\r\nCH %lf\r\nQRSTUV\r\n",
			rand()%100,
			(dialog->odometer+(5)),
			rand()%200,
			rand()%200,
			rand()%20,
			rand()%100,
			rand()%120,
			(rand()%100/100.));

		//process a packet
		sscanf(dialog->buffer,"ABCDEF\r\nTI %d\r\nOD %d\r\nTM %d\r\nTC %d\r\nVO %d\r\nCU %d\r\nSP %d\r\nCH %lf\r\nQRSTUV\r\n",
				&dialog->Time,
				&dialog->odometer,
				&dialog->tempMotor,
				&dialog->tempCont,
				&dialog->voltage,
				&dialog->current,
				&dialog->speed,
				&dialog->charge);	
		//log packet to tab delimited file
		//fprintf(record,"%d\t%d\t%d\t%d\t%d\t%d\t%d\t%lf\n",dialog->Time,dialog->odometer,dialog->tempMotor,dialog->tempCont,dialog->voltage,dialog->current,dialog->speed,dialog->charge);

		emit dashboardUpdated();

		graph[0].Plot(2,dialog->odometer,dialog->charge);	
	
		if(dialog->odometer/xmax > .5){
			GracePrintf("Autoscale xaxes");
			//xmin+=scroll;
			//xmax+=scroll;
			GracePrintf("With G0");
			//GracePrintf("World xmin %f",xmin);
			//GracePrintf("World xmax %f",xmax);
			GracePrintf("Autoscale yaxes");
		}
	
		 	graph.redraw();   //  Send "redraw" command to Grace
		sleep(1);
	}
	if((last = fopen("Position.dat","w")) == NULL){
		fprintf(stderr,"Couldn't open yesterdays position!\n");
	}
	else{
		fprintf(last,"%d\n",dialog->odometer);
	}
	fclose(last);

}

void WorkerThread::initializeGraph(){
	xmax = 100;
	xmin = 0;
	scroll = 10;
	GracePrintf("With G0");
	GracePrintf("READ XY \"data.log\"");
	GracePrintf("READ XY \"waypoints.dat\"");
	GracePrintf("World xmax 100");
}

